291
-extension PhotoDetailViewController: CellDelegate {
292
-    func selectIndex(indexpath: IndexPath) {
293
-        let ctl = UIStoryboard.photoDetail.instantiateController(ShowFullPicController.self)
294
-        ctl.datas = datas
295
-        ctl.currentPhotoIndex = currentPhotoIndex
296
-        show(ctl, sender: nil)
187
+    
188
+    func bindViewModelToGroupAvatar() {
189
+        viewModel.groupAvatar
190
+            .subscribe(onNext: {[weak self] (avatar) in
191
+            guard let `self` = self else { return }
192
+            self.groupAvatar.setImage(avatar)
193
+        }).disposed(by: disposeBag)
297 194
     }
298
-
299
-    func returnCurrentIndex(index: Int) {
300
-        refreshUI(index: index)
195
+    
196
+    func bindgingViewModelToUserAvatar() {
197
+        viewModel.userAvatar
198
+            .subscribe(onNext: {[weak self] (avatar) in
199
+                guard let `self` = self else { return }
200
+                self.userAvatar.setImage(avatar)
201
+            }).disposed(by: disposeBag)
301 202
     }
302
-
303
-    func pushNext() {
304
-        let ctl = UIStoryboard.main.instantiateController(GroupViewController.self)
305
-
306
-//        ctl.groupModel = GroupModel(map: Map(mappingType: .fromJSON, JSON: datas[currentPhotoIndex].toJSON()))
307
-        show(ctl, sender: nil)
203
+    
204
+    func bindViewModelToUserName() {
205
+        viewModel.groupName.bind(to: userName.rx.text).disposed(by: disposeBag)
308 206
     }
309
-}
310
-
311
-//MARK textField delegate
312
-extension PhotoDetailViewController: UIGestureRecognizerDelegate {
313
-    // MARK: textField
314
-
315
-    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
316
-        return commentTextField.isFirstResponder
207
+    
208
+    func bindViewModelToPhotoTime() {
209
+        viewModel.photoTime.bind(to: photoTime.rx.text).disposed(by: disposeBag)
317 210
     }
318
-
319
-    @IBAction func ReturnKeyboard(_ sender: UITapGestureRecognizer) {
320
-        if !commentView.isHidden {
321
-            commentTextField.resignFirstResponder()
322
-            commentView.isHidden = true
323
-        }
211
+    
212
+    func bindViewModelToThumbupCount() {
213
+        viewModel.thumbupCount.bind(to: thumbupCount.rx.text).disposed(by: disposeBag)
324 214
     }
325
-
326
-}
327
-
328
-// MARK: UITableView delegate
329
-extension PhotoDetailViewController: UITableViewDataSource, UITableViewDelegate {
330
-
331
-    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
332
-        if section == 3 {
333
-            let cell = tableView.dequeueReusableCell(withIdentifier: "thumbupHeadCell")
334
-            if let label = cell?.viewWithTag(1001) as? UILabel {
335
-//                label.text = "(\(detailPageViewModel.thumbups.count))"
336
-            }
337
-            if let button = cell?.viewWithTag(1011) as? UIButton {
338
-                button.addTarget(self, action: #selector(showThumps), for: .touchUpInside)
339
-            }
340
-            if let imageView = cell?.viewWithTag(1008) as? UIImageView {
341
-//                let imageName = detailPageViewModel.thumbupsCount <= 0 ? "收起" : "list-arrow"
342
-//                imageView.image = UIImage(named : imageName)
343
-            }
344
-            return cell?.contentView
345
-        } else if section == 4 {
346
-            let cell = tableView.dequeueReusableCell(withIdentifier: "comentHeadCell")
347
-            if let label = cell?.viewWithTag(1002) as? UILabel {
348
-//                label.text = "(\(detailPageViewModel.comments.count))"
349
-            }
350
-            if let button = cell?.viewWithTag(1012) as? UIButton {
351
-                button.addTarget(self, action: #selector(showComments), for: .touchUpInside)
352
-            }
353
-            if let imageView = cell?.viewWithTag(1009) as? UIImageView {
354
-//                let imageName = detailPageViewModel.commentsCount <= 0 ? "收起" : "list-arrow"
355
-//                imageView.image = UIImage(named : imageName)
356
-            }
357
-            return cell?.contentView
358
-        }
359
-        return nil
215
+    
216
+    func bindViewModelToThumbupView() {
217
+        viewModel.thumbupItems
218
+            .asDriver(onErrorJustReturn: [])
219
+            .drive(onNext: { [weak self] (items) in
220
+                self?.setupThumbupView(items: items)
221
+            }).disposed(by: disposeBag)
360 222
     }
361
-
362
-    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
363
-        if section == 3 || section == 4 {
364
-            return 44
365
-        }
366
-        return 0
223
+    
224
+    func bindViewModelToCommentCount() {
225
+        viewModel.commentCount.bind(to: commentCount.rx.text).disposed(by: disposeBag)
367 226
     }
368
-
369
-    func numberOfSections(in tableView: UITableView) -> Int {
370
-        return 0
227
+    
228
+    func bindViewModelToCommentTableView() {
229
+        viewModel.commentItems
230
+            .bind(to: commentTableView.rx.items(dataSource: commentTableViewDataSource))
231
+            .disposed(by: disposeBag)
371 232
     }
372
-
373
-    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
374
-//        if section == 3 {
375
-//            return detailPageViewModel.thumbupsCount > 0 ? 1 : 0
376
-//        } else if section == 4 {
377
-//            return detailPageViewModel.commentsCount
378
-//        }
379
-        return 0
233
+    
234
+    func bindBuyViewIsVisiable() {
235
+        viewModel.canBuy.map { !$0 }.bind(to: buyView.rx.isHidden).disposed(by: disposeBag)
380 236
     }
381
-
382
-    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
383
-        if indexPath.section == 0 {
384
-            let cell = tableView.dequeueReusableCell(withIdentifier: "headCell", for: indexPath) as! DetailPageHeadCell
385
-            cell.enterView.isHidden = isHiddenEnterView
386
-//            cell.setInfo(datas[currentPhotoIndex])
387
-            cell.delegate = self
388
-            if let reportBtn = cell.viewWithTag(40001) as? UIButton {
389
-
390
-                reportBtn.addTarget(self, action: #selector(loadReportController), for: .touchUpInside)
391
-//                reportBtn.isHidden = !(UserDefaults.Account.bool(forKey: .isAudit))
392
-            }
393
-            return cell
394
-        } else if indexPath.section == 1 {
395
-            let cell = tableView.dequeueReusableCell(withIdentifier: "detailPagePhotoCell", for: indexPath) as! DetailPagePhotoCell
396
-//            cell.datas = datas
397
-//            cell.currentPhotoIndex = currentPhotoIndex
398
-            cell.delegate = self
399
-            cell.first = true
400
-            cell.collectionView.reloadData()
401
-            return cell
402
-        } else if indexPath.section == 2 {
403
-            let cell = tableView.dequeueReusableCell(withIdentifier: "nameCell", for: indexPath) as! DetailPageNameCell
404
-//            cell.setInfo(datas[currentPhotoIndex])
405
-            return cell
406
-        } else if indexPath.section == 3 {
407
-            let cell = tableView.dequeueReusableCell(withIdentifier: "thumbupCell", for: indexPath) as! DetailthumbupImagesCell
408
-//            if detailPageViewModel.thumbups.count > 0 {
409
-//                let headers = detailPageViewModel.thumbups.map {$0.avatar}
410
-//                cell.setInfo(content: headers)
411
-//            }
412
-            return cell
413
-        } else {
414
-            let cell = tableView.dequeueReusableCell(withIdentifier: "comentCell", for: indexPath) as! DetailCommentCell
415
-//            cell.setInfo(detailPageViewModel.comments[indexPath.row])
416
-            return cell
417
-        }
237
+    
238
+    func bindCommentTextFieldToSendBtn() {
239
+        commentTextField.rx.text
240
+            .map { !($0?.isEmpty)! }
241
+            .bind(to: sendBtn.rx.isEnabled)
242
+            .disposed(by: disposeBag)
243
+    }
244
+    
245
+    func bindCollectionViewDelegate() {
246
+        photoCollectionView.rx.setDelegate(self).disposed(by: disposeBag)
247
+        
248
+    }
249
+    
250
+    func bindListViewModelToCollectionView() {
251
+        listViewModel.content
252
+            .bind(to: photoCollectionView.rx.items(dataSource: photoCollectionViewDataSource))
253
+            .disposed(by: disposeBag)
254
+    }
255
+    
256
+    func bindCollectionViewToListViewModel() {
257
+        photoCollectionView.rx.willDisplayCell
258
+            .asDriver()
259
+            .drive(onNext: { [unowned self] in
260
+                self.listViewModel.willShow(index: $0.at.row)
261
+            })
262
+            .disposed(by: disposeBag)
263
+    }
264
+    
265
+    func bindCollectionViewSelected() {
266
+        photoCollectionView.rx.itemSelected
267
+            .asDriver(onErrorJustReturn: IndexPath(item: 0, section: 0))
268
+            .drive(onNext: { [unowned self] _ in self.listViewModel.didSelected() })
269
+            .disposed(by: disposeBag)
270
+    }
271
+    
272
+    func bindViewWillAppear() {
273
+        viewModel.viewWillAppear
274
+            .asDriver()
275
+            .drive(onNext: { [unowned self] _ in
276
+                self.photoCollectionView.scrollToItem(at: IndexPath(item: self.listViewModel.currIndex, section: 0), at: .right, animated: false)
277
+            })
278
+            .disposed(by: disposeBag)
418 279
     }
280
+    
281
+    func monitorKeyboardWillShow() {
282
+        NotificationCenter.default.rx
283
+            .notification(UIResponder.keyboardWillShowNotification)
284
+            .takeUntil(self.rx.deallocated)
285
+            .subscribe { [unowned self] notification in
286
+                guard let userInfo = notification.element?.userInfo,
287
+                    let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
288
+                    let timeInterval = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval,
289
+                    let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int
290
+                    else { return }
291
+                UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: curve) ?? .linear)
292
+                UIView.animate(withDuration: timeInterval, animations: {
293
+                    self.commentEditYConstraint.constant = keyboardFrame.height
294
+                    self.view.layoutIfNeeded()
295
+                })
296
+        }.disposed(by: disposeBag)
297
+    }
298
+    
299
+    func monitorKeyboardWillHide() {
300
+        NotificationCenter.default.rx
301
+            .notification(UIResponder.keyboardWillHideNotification)
302
+            .takeUntil(self.rx.deallocated)
303
+            .subscribe { [unowned self] notification in
304
+                guard let userInfo = notification.element?.userInfo,
305
+                    let timeInterval = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval,
306
+                    let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int
307
+                    else { return }
308
+                UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: curve) ?? .linear)
309
+                UIView.animate(withDuration: timeInterval, animations: {
310
+                    self.commentEditYConstraint.constant = -56
311
+                    self.view.layoutIfNeeded()
312
+                })
313
+                self.commentTextField.clear()
314
+        }.disposed(by: disposeBag)
315
+    }
316
+}
419 317
 
420
-    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
421
-        if indexPath.section == 0 {
422
-            return 48
423
-        } else if indexPath.section == 1 {
424
-            return 360
425
-        } else if indexPath.section == 2 {
426
-            return 36
427
-        } else if indexPath.section == 3 {
428
-            return 40
429
-        } else {
430
-//            return 40 + detailPageViewModel.comments[indexPath.row].cellHeigth
431
-            return 40
318
+extension PhotoDetailViewController {
319
+    func setupThumbupView(items: [PhotoThumbupUserItem]) {
320
+        thumbupView.subviews.forEach { $0.removeFromSuperview() }
321
+        
322
+        let row = (Int(kScreenWidth) - 6) / 34
323
+        var topConstraint: CGFloat = 6
324
+        var last: UIImageView?
325
+        
326
+        for (index, item) in items.enumerated() {
327
+            let imageView = UIImageView()
328
+            imageView.cornerRadius = 5
329
+            imageView.translatesAutoresizingMaskIntoConstraints = false
330
+            imageView.setImage(item.avatar, placeholder: UIImage.defaultAvatar)
331
+            thumbupView.addSubview(imageView)
332
+            
333
+            if index % row == 0 && index != 0 {
334
+                topConstraint += 28 + 6
335
+                last = nil
336
+            }
337
+            
338
+            NSLayoutConstraint.activate([
339
+                imageView.widthAnchor.constraint(equalToConstant: 28),
340
+                imageView.heightAnchor.constraint(equalToConstant: 28),
341
+                imageView.topAnchor.constraint(equalTo: thumbupView.topAnchor, constant: topConstraint),
342
+                imageView.leadingAnchor.constraint(equalTo: last?.trailingAnchor ?? thumbupView.leadingAnchor, constant: 6)
343
+                ])
344
+            
345
+            last = imageView
432 346
         }
347
+        thumbupViewHeightConstraint.constant = items.isEmpty ? 1 : topConstraint + 34
348
+        commentTableView.tableHeaderView?.height = 532 + thumbupViewHeightConstraint.constant
433 349
     }
434 350
 }
435 351
 
436
-extension PhotoDetailViewController {
352
+extension PhotoDetailViewController: UICollectionViewDelegateFlowLayout {
353
+    func collectionView(_ collectionView: UICollectionView,
354
+                        layout collectionViewLayout: UICollectionViewLayout,
355
+                        sizeForItemAt indexPath: IndexPath) -> CGSize {
356
+        return CGSize(width: kScreenWidth, height: 359)
357
+    }
437 358
     
359
+    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
360
+        return 0
361
+    }
438 362
 }
363
+
364
+extension PhotoDetailViewController: NavigationBackViewController {}

+ 90 - 75
PaiAi/Paiai_iOS/App/PhotoDetail/PhotoPreviewViewController.swift

@@ -1,5 +1,5 @@
1 1
 //
2
-//  ShowFullPicController.swift
2
+//  PhotoPreviewViewController.swift
3 3
 //  PaiAi
4 4
 //
5 5
 //  Created by zhengjianfei on 16/4/9.
@@ -9,49 +9,104 @@
9 9
 import UIKit
10 10
 import PaiaiDataKit
11 11
 import PaiaiUIKit
12
+import RxCocoa
13
+import RxSwift
14
+import RxDataSources
12 15
 
13
-final class ShowFullPicController: UIViewController {
16
+final class PhotoPreviewViewController: UIViewController {
14 17
 
15
-    // MARK: Storyboard property
18
+    /// MARK: Storyboard property
16 19
     @IBOutlet weak var collectionView: UICollectionView!
17
-//    @IBOutlet weak var progressView: FFProgress!
18
-   // MARK: parameter property
19
-    lazy var datas = [PhotoItem]()
20
-    lazy var currentPhotoIndex = 0
21
-    lazy var firstLayout = true
22
-    lazy var currentPageIndex = 0
23
-    lazy var showNomark = false
24
-    lazy var showHD = false
25
-
26
-    var shufflingImage = [String]()
27
-
28
-    // MARK: Controller fucntion
20
+    var viewModel: PhotoDetailListViewModel!
21
+    var disposeBag = DisposeBag()
22
+    
23
+    override var prefersStatusBarHidden: Bool {
24
+        return true
25
+    }
26
+    
29 27
     override func viewDidLoad() {
30 28
         super.viewDidLoad()
31
-        navigationController?.isNavigationBarHidden = true
32
-//        titleWithbackBar = ""
33
-
34
-     }
35
-
36
-    override func viewDidLayoutSubviews() {
37
-        if firstLayout {
38
-            collectionView.contentOffset = CGPoint(x: (CGFloat(currentPhotoIndex) * (collectionView.width)), y: 0)
39
-            firstLayout = false
29
+        binding()
30
+        scrollToSpecifiedImage()
31
+        navigationController?.setNavigationBarHidden(true, animated: true)
32
+        
33
+    }
34
+    
35
+    func scrollToSpecifiedImage() {
36
+        collectionView.layoutIfNeeded()
37
+        collectionView.scrollToItem(at: IndexPath(item: viewModel.currIndex, section: 0), at: .right, animated: false)
38
+    }
39
+    
40
+    override func viewDidAppear(_ animated: Bool) {
41
+        super.viewWillAppear(animated)
42
+        bindCollectionViewToViewModel()
43
+    }
44
+    
45
+    override func viewWillDisappear(_ animated: Bool) {
46
+        super.viewWillDisappear(animated)
47
+        navigationController?.setNavigationBarHidden(false, animated: true)
48
+    }
49
+    
50
+    @IBAction func download(_ sender: UIButton) {
51
+        guard let cell = collectionView.cellForItem(at: IndexPath(item: viewModel.currIndex, section: 0)) as? ImageCell,
52
+            let image = cell.photoImage.image else {
53
+                //            FFToastView.showToast(inView: view, withText: "未检测到图片")
54
+                return
40 55
         }
41
-        super.viewDidLayoutSubviews()
56
+        
57
+        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
42 58
     }
59
+    
60
+    @objc func image(_ image: UIImage?, didFinishSavingWithError error: NSError?, contextInfo info: UnsafeMutableRawPointer) {
61
+        if error != nil {
62
+            //            FFToastView.showToast(inView: view, withText: "保存图片失败")
63
+        } else {
64
+            //            FFToastView.showImageToast(inView: view, withText: "已保存图片到相册", withImage: "提示弹窗-勾")
65
+        }
66
+    }
67
+}
68
+
69
+/// binding
70
+extension PhotoPreviewViewController {
71
+    
72
+    var dataSource: RxCollectionViewSectionedAnimatedDataSource<AnimatableSectionModel<Int, PhotoItem>> {
73
+        return RxCollectionViewSectionedAnimatedDataSource<AnimatableSectionModel<Int, PhotoItem>>(configureCell: { (dataSource, collectionView, indexPath, item) in
74
+            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCell
75
+            cell.setModel(url: item.murl.isEmpty ? item.photo_url : item.murl)
76
+            return cell
77
+        })
78
+    }
79
+    
80
+    func binding() {
81
+        bindViewModelToCollectionView()
82
+        bindCollectionViewDelegate()
83
+    }
84
+    
85
+    func bindViewModelToCollectionView() {
86
+        viewModel.content
87
+            .bind(to: collectionView.rx.items(dataSource: dataSource))
88
+            .disposed(by: disposeBag)
89
+    }
90
+    
91
+    func bindCollectionViewDelegate() {
92
+        collectionView.rx.setDelegate(self).disposed(by: disposeBag)
93
+    }
94
+    
95
+    func bindCollectionViewToViewModel() {
96
+        collectionView.rx.willDisplayCell
97
+            .asDriver()
98
+            .drive(onNext: { [unowned self] in self.viewModel.willShow(index: $0.at.row) })
99
+            .disposed(by: disposeBag)
100
+    }
101
+}
43 102
 
44
-    // MARK: Storyboard  button function
103
+/// storyboard button action
104
+extension PhotoPreviewViewController {
45 105
     @IBAction  func back() {
46
-         _ = navigationController?.popViewController(animated: true)
47
-        guard let ctl = navigationController?.viewControllers.last as? PhotoDetailViewController else {
48
-            return
49
-        }
50
-//        ctl.currentPhotoIndex = currentPageIndex
51
-//        ctl.tableView.reloadData()
106
+        navigationController?.popViewController(animated: true)
52 107
     }
53 108
     @IBAction func rotateTheImage(_ sender: UIButton) {
54
-        guard let cell = collectionView.cellForItem(at: IndexPath(item: currentPageIndex, section: 0)) as? ImageCell else {
109
+        guard let cell = collectionView.cellForItem(at: IndexPath(item: viewModel.currIndex, section: 0)) as? ImageCell else {
55 110
             return
56 111
         }
57 112
         UIView.beginAnimations("image.rotate", context: nil)
@@ -71,54 +126,14 @@ final class ShowFullPicController: UIViewController {
71 126
             }
72 127
         }
73 128
     }
129
+    
74 130
 
75
-    @IBAction func load() {
76
-        guard let cell = collectionView.cellForItem(at: IndexPath(item: currentPageIndex, section: 0)) as? ImageCell else {
77
-//            FFToastView.showToast(inView: view, withText: "未检测到图片")
78
-            return
79
-        }
80
-        guard let image = cell.photoImage.image else {
81
-//            FFToastView.showToast(inView: view, withText: "未检测到图片")
82
-            return
83
-        }
84
-        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
85
-    }
86
-
87
-    @objc func image(_ image: UIImage?, didFinishSavingWithError error: NSError?, contextInfo info: UnsafeMutableRawPointer) {
88
-        if error != nil {
89
-//            FFToastView.showToast(inView: view, withText: "保存图片失败")
90
-        } else {
91
-//            FFToastView.showImageToast(inView: view, withText: "已保存图片到相册", withImage: "提示弹窗-勾")
92
-        }
93
-
94
-    }
95 131
 }
96 132
 
97 133
 // MARK: UICollectionView delegate
98
-extension ShowFullPicController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
99
-
100
-    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
101
-        return shufflingImage.count > datas.count ? shufflingImage.count : datas.count
102
-    }
103
-
104
-    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
105
-        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCell
106
-        if shufflingImage.count <= 0 {
107
-            let data = datas[indexPath.item]
108
-            let urlStr = data.murl.isEmpty ? data.photo_url : data.murl
109
-            cell.setModel(url: urlStr)
110
-        } else {
111
-            cell.setModel(url: shufflingImage[indexPath.row])
112
-        }
113
-        return cell
114
-    }
134
+extension PhotoPreviewViewController: UICollectionViewDelegateFlowLayout {
115 135
 
116 136
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
117 137
         return CGSize(width: collectionView.width, height: collectionView.height - 20)
118 138
     }
119
-
120
-    func scrollViewDidScroll(_ scrollView: UIScrollView) {
121
-        let page = Int(scrollView.contentOffset.x / (collectionView.width))
122
-        currentPageIndex = page
123
-    }
124 139
 }

+ 15 - 7
PaiAi/Paiai_iOS/App/PhotoDetail/ShareView.swift

@@ -9,13 +9,21 @@
9 9
 import UIKit
10 10
 
11 11
 class ShareView: UIView {
12
+    
13
+}
14
+
12 15
 
13
-    /*
14
-    // Only override draw() if you perform custom drawing.
15
-    // An empty implementation adversely affects performance during animation.
16
-    override func draw(_ rect: CGRect) {
17
-        // Drawing code
18
-    }
19
-    */
20 16
 
17
+extension ShareView {
18
+    
19
+    func activateConstraints() {
20
+        
21
+    }
22
+    
23
+    func activateConstraintsShareView() {
24
+        guard let superView = superview else { return }
25
+        
26
+        self.translatesAutoresizingMaskIntoConstraints = false
27
+        
28
+    }
21 29
 }

+ 0 - 15
PaiAi/launch_multiple_simulators.sh

@@ -1,15 +0,0 @@
1
-#!/bin/bash
2
-
3
-xcrun simctl shutdown all
4
-
5
-path=$(find ~/Library/Developer/Xcode/DerivedData/Paiai-*/Build/Products/Debug-iphonesimulator -name "Paiai.app" | head -n 1)
6
-echo "${path}"
7
-
8
-filename=MultiSimConfig.txt
9
-grep -v '^#' $filename | while read -r line
10
-do
11
-  echo $line
12
-  xcrun instruments -w "$line"
13
-  xcrun simctl install booted $path
14
-  xcrun simctl launch booted com.Paiai.Paiai
15
-done

购买调整 · f4e1f54527 - Gogs: Go Git Service

购买调整

chengzhenyu 9 years ago
parent
commit
f4e1f54527

+ 3 - 6
app/src/main/java/ai/pai/lensman/bean/OrderBean.java

@@ -1,14 +1,11 @@
1 1
 package ai.pai.lensman.bean;
2 2
 
3
-/**
4
- * Created by chengzhenyu on 2016/8/27.
5
- */
6 3
 
7 4
 public class OrderBean {
8
-    public String orderId;
9
-    public float orderMoney;
10
-    public long orderTime;
5
+    public String photoId;
6
+    public String sessionId;
11 7
     public String buyerId;
12 8
     public String buyerName;
9
+    public long originExpireTime;
13 10
     public PhotoBean photoBean;
14 11
 }

+ 0 - 49
app/src/main/java/ai/pai/lensman/db/DBHelper.java

@@ -26,28 +26,6 @@ public class DBHelper extends SQLiteOpenHelper{
26 26
 
27 27
     }
28 28
 
29
-    public static final String ORDER_INFO_TABLE = "order_info_table";
30
-
31
-    public interface ORDER_INFO_COLUMNS {
32
-        String ORDER_ID = "order_id";
33
-        String ORDER_MONEY = "order_money";
34
-        String ORDER_TIME = "order_time";
35
-        String BUYER_ID = "buyer_id";
36
-        String BUYER_NAME = "buyer_name";
37
-        String PHOTO_ID = "photo_id";
38
-        String PHOTO_NAME = "photo_name";
39
-        String PHOTO_PATH = "photo_path";
40
-        String CAPTURE_TIME = "capture_time";
41
-        String SESSION_ID = "session_id";
42
-        String LENSMAN_ID = "lensman_id";
43
-        String SESSION_DATE = "session_date";
44
-        String SESSION_SEQ = "session_seq";
45
-        String IS_RAW_PHOTO= "is_raw_photo";
46
-        String UPLOADED_STATUS = "upload_status";
47
-
48
-    }
49
-
50
-
51 29
     private DBHelper(Context context){
52 30
         super(context,DB_NAME,null,DB_VERSION);
53 31
     }
@@ -71,10 +49,8 @@ public class DBHelper extends SQLiteOpenHelper{
71 49
 
72 50
     private void createTables(SQLiteDatabase db){
73 51
         createPhotoTable(db,PHOTO_INFO_TABLE);
74
-        createOrderTable(db,ORDER_INFO_TABLE);
75 52
     }
76 53
 
77
-
78 54
     private void createPhotoTable(SQLiteDatabase db, String tableName){
79 55
         StringBuilder sql = new StringBuilder();
80 56
         sql.append("CREATE TABLE IF NOT EXISTS ");
@@ -93,29 +69,4 @@ public class DBHelper extends SQLiteOpenHelper{
93 69
         db.execSQL(sql.toString());
94 70
     }
95 71
 
96
-    private void createOrderTable(SQLiteDatabase db, String tableName){
97
-        StringBuilder sql = new StringBuilder();
98
-        sql.append("CREATE TABLE IF NOT EXISTS ");
99
-        sql.append(tableName).append("(");
100
-        sql.append(ORDER_INFO_COLUMNS.PHOTO_ID).append(" LONG PRIMARY KEY, ");
101
-
102
-        sql.append(ORDER_INFO_COLUMNS.ORDER_ID).append(" VARCHAR, ");
103
-        sql.append(ORDER_INFO_COLUMNS.BUYER_ID).append(" VARCHAR, ");
104
-        sql.append(ORDER_INFO_COLUMNS.BUYER_NAME).append(" VARCHAR, ");
105
-        sql.append(ORDER_INFO_COLUMNS.ORDER_MONEY).append(" FLOAT, ");
106
-        sql.append(ORDER_INFO_COLUMNS.ORDER_TIME).append(" LONG, ");
107
-
108
-        sql.append(ORDER_INFO_COLUMNS.PHOTO_NAME).append(" VARCHAR, ");
109
-        sql.append(ORDER_INFO_COLUMNS.PHOTO_PATH).append(" VARCHAR, ");
110
-        sql.append(ORDER_INFO_COLUMNS.LENSMAN_ID).append(" VARCHAR, ");
111
-        sql.append(ORDER_INFO_COLUMNS.SESSION_ID).append(" VARCHAR, ");
112
-        sql.append(ORDER_INFO_COLUMNS.IS_RAW_PHOTO).append(" INTEGER, ");
113
-        sql.append(ORDER_INFO_COLUMNS.SESSION_SEQ).append(" INTEGER, ");
114
-        sql.append(ORDER_INFO_COLUMNS.SESSION_DATE).append(" LONG, ");
115
-        sql.append(ORDER_INFO_COLUMNS.UPLOADED_STATUS).append(" INTEGER, ");
116
-        sql.append(ORDER_INFO_COLUMNS.CAPTURE_TIME).append(" LONG ");
117
-        sql.append(")");
118
-        db.execSQL(sql.toString());
119
-    }
120
-
121 72
 }

+ 1 - 109
app/src/main/java/ai/pai/lensman/db/DBService.java

@@ -10,7 +10,6 @@ import com.android.common.utils.LogHelper;
10 10
 import java.util.ArrayList;
11 11
 
12 12
 import ai.pai.lensman.App;
13
-import ai.pai.lensman.bean.OrderBean;
14 13
 import ai.pai.lensman.bean.PhotoBean;
15 14
 import ai.pai.lensman.bean.SessionBean;
16 15
 
@@ -18,7 +17,7 @@ import ai.pai.lensman.bean.SessionBean;
18 17
 public class DBService {
19 18
 
20 19
     private static DBService instance;
21
-    private static Object DB_LOCK = new Object();
20
+    private static final Object DB_LOCK = new Object();
22 21
     private DBHelper dbHelper;
23 22
 
24 23
     private static final String TAG = "DBService";
@@ -235,14 +234,6 @@ public class DBService {
235 234
                 if (c.moveToNext()) {
236 235
                     photoBean = cursor2PhotoBean(c);
237 236
                 }
238
-//                else {
239
-//                    c = db.rawQuery("select * from " + DBHelper.PHOTO_INFO_TABLE +  " where "
240
-//                            + DBHelper.PHOTO_INFO_COLUMNS.UPLOADED_STATUS + " = '" + -1 + "'"+"  order by "
241
-//                            + DBHelper.PHOTO_INFO_COLUMNS.CAPTURE_TIME + " desc limit 1 ", null);
242
-//                    if (c.moveToNext()) {
243
-//                        photoBean = cursor2PhotoBean(c);
244
-//                    }
245
-//                }
246 237
                 db.setTransactionSuccessful();
247 238
             } catch (Exception e) {
248 239
                 LogHelper.d(TAG, "dbservice getNextUploadPhotoBean error happen " + e);
@@ -258,103 +249,4 @@ public class DBService {
258 249
         return photoBean;
259 250
     }
260 251
 
261
-    public void addOrderBean(OrderBean bean){
262
-        SQLiteDatabase db = null;
263
-        synchronized (DB_LOCK) {
264
-            try {
265
-                db = dbHelper.getWritableDatabase();
266
-                db.beginTransaction();
267
-                db.insertWithOnConflict(DBHelper.ORDER_INFO_TABLE, null, orderBean2ContentValues(bean),
268
-                        SQLiteDatabase.CONFLICT_REPLACE);
269
-                db.setTransactionSuccessful();
270
-            } catch (Exception e) {
271
-                LogHelper.d(TAG, "dbservice addOrderBean error happen " + e);
272
-            } finally {
273
-                try {
274
-                    db.endTransaction();
275
-                } catch (Exception e) {
276
-                    e.printStackTrace();
277
-                }
278
-                closeDB(db);
279
-            }
280
-        }
281
-    }
282
-
283
-    public void updateOrderBean(OrderBean bean){
284
-        addOrderBean(bean);
285
-    }
286
-
287
-
288
-    private OrderBean cursor2OrderBean(Cursor c) {
289
-        OrderBean item = new OrderBean();
290
-        item.buyerId = c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.BUYER_ID));
291
-        item.buyerName= c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.BUYER_NAME));
292
-        item.orderId = c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.ORDER_ID));
293
-        item.orderMoney= c.getFloat(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.ORDER_MONEY));
294
-        item.orderTime = c.getLong(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.ORDER_TIME));
295
-        item.photoBean = new PhotoBean();
296
-        item.photoBean.lensmanId = c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.LENSMAN_ID));
297
-        item.photoBean.sessionId = c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.SESSION_ID));
298
-        item.photoBean.isRawPhoto =(c.getInt(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.IS_RAW_PHOTO))>0);
299
-        item.photoBean.uploadStatus = c.getInt(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.UPLOADED_STATUS));
300
-        item.photoBean.captureTime = c.getLong(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.CAPTURE_TIME));
301
-        item.photoBean.photoId = c.getLong(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.PHOTO_ID));
302
-        item.photoBean.photoName = c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.PHOTO_NAME));
303
-        item.photoBean.photoPath = c.getString(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.PHOTO_PATH));
304
-        item.photoBean.sessionDate = c.getLong(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.SESSION_DATE));
305
-        item.photoBean.sessionSeq = c.getInt(c.getColumnIndex(DBHelper.ORDER_INFO_COLUMNS.SESSION_SEQ));
306
-        return item;
307
-    }
308
-
309
-    private ContentValues orderBean2ContentValues(OrderBean orderBean) {
310
-        ContentValues cv = new ContentValues();
311
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.BUYER_ID, orderBean.buyerId);
312
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.BUYER_NAME,orderBean.buyerName);
313
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.ORDER_ID,orderBean.orderId);
314
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.ORDER_MONEY,orderBean.orderMoney);
315
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.ORDER_TIME,orderBean.orderTime);
316
-        PhotoBean item = orderBean.photoBean;
317
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.CAPTURE_TIME, item.captureTime);
318
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.IS_RAW_PHOTO, item.isRawPhoto ? 1: 0);
319
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.PHOTO_ID, item.photoId);
320
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.PHOTO_NAME, item.photoName);
321
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.PHOTO_PATH, item.photoPath);
322
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.SESSION_ID, item.sessionId);
323
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.LENSMAN_ID,item.lensmanId);
324
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.UPLOADED_STATUS,item.uploadStatus);
325
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.SESSION_DATE,item.sessionDate);
326
-        cv.put(DBHelper.ORDER_INFO_COLUMNS.SESSION_SEQ,item.sessionSeq);
327
-        return cv;
328
-    }
329
-
330
-    public OrderBean getNextDealOrder(){
331
-        LogHelper.d(TAG, "dbservice getNextDealOrder ");
332
-        OrderBean orderBean = null;
333
-        SQLiteDatabase db = null;
334
-        Cursor c = null;
335
-        synchronized (DB_LOCK) {
336
-            try {
337
-                db = dbHelper.getReadableDatabase();
338
-                db.beginTransaction();
339
-                c = db.rawQuery("select * from " + DBHelper.ORDER_INFO_TABLE +  " where "
340
-                        + DBHelper.ORDER_INFO_COLUMNS.UPLOADED_STATUS + " = '" + 0 + "'"+"  order by "
341
-                        + DBHelper.ORDER_INFO_COLUMNS.ORDER_TIME + " desc limit 1 ", null);
342
-                if (c.moveToNext()) {
343
-                    orderBean = cursor2OrderBean(c);
344
-                }
345
-                db.setTransactionSuccessful();
346
-            } catch (Exception e) {
347
-                LogHelper.d(TAG, "dbservice getNextDealOrder error happen " + e);
348
-            } finally {
349
-                try {
350
-                    db.endTransaction();
351
-                } catch (Exception e) {
352
-                    e.printStackTrace();
353
-                }
354
-                closeCursorAndDB(c, db);
355
-            }
356
-        }
357
-        return orderBean;
358
-    }
359
-
360 252
 }

+ 25 - 12
app/src/main/java/ai/pai/lensman/service/OrderDealService.java

@@ -21,10 +21,9 @@ import java.net.HttpURLConnection;
21 21
 import java.net.URL;
22 22
 import java.util.ArrayList;
23 23
 import java.util.HashMap;
24
-import java.util.Timer;
25
-import java.util.TimerTask;
26 24
 
27 25
 import ai.pai.lensman.bean.OrderBean;
26
+import ai.pai.lensman.bean.PhotoBean;
28 27
 import ai.pai.lensman.db.Preferences;
29 28
 import ai.pai.lensman.utils.BoxUrlContainer;
30 29
 import ai.pai.lensman.utils.Constants;
@@ -72,13 +71,18 @@ public class OrderDealService extends Service implements Handler.Callback{
72 71
                     int status = json.getInt("status");
73 72
                     if (status == 200) {
74 73
                         JSONObject data = json.getJSONObject("data");
75
-                        JSONArray orders = data.getJSONArray("files");
74
+                        JSONArray orders = data.getJSONArray("wanted");
76 75
                         if (orders != null && orders.length() > 0) {
77 76
                             orderList = new ArrayList<OrderBean>();
78 77
                             for (int k = 0; k < orders.length(); k++) {
79 78
                                 JSONObject orderObj = orders.getJSONObject(k);
80 79
                                 OrderBean bean = new OrderBean();
81
-
80
+                                bean.sessionId = orderObj.getString("session_id");
81
+                                bean.photoId = orderObj.getString("photo_id");
82
+                                JSONObject photoObj = orderObj.getJSONObject("group_photo_info");
83
+                                bean.buyerId = photoObj.getString("user_id");
84
+                                bean.buyerName = photoObj.getString("nickname");
85
+                                bean.originExpireTime = photoObj.getLong("origin_expired_stamps");
82 86
                                 orderList.add(bean);
83 87
                             }
84 88
                         }
@@ -116,13 +120,12 @@ public class OrderDealService extends Service implements Handler.Callback{
116 120
         }
117 121
     }
118 122
 
119
-    private void fetchOriginFromBox(OrderBean orderBean) {
123
+    private void fetchOriginFromBox(final OrderBean orderBean) {
120 124
         HashMap<String, String> params = new HashMap<>();
121 125
         params.put("lensman", Preferences.getInstance().getLensManId());
122
-        params.put("session", orderBean.photoBean.sessionId);
123
-        params.put("name", orderBean.photoBean.photoName);
126
+        params.put("session", orderBean.sessionId);
127
+        params.put("name", orderBean.photoId);
124 128
         new HttpPostTask(params) {
125
-            OrderBean bean = new OrderBean();
126 129
 
127 130
             @Override
128 131
             protected boolean parseResponse(String response) {
@@ -132,7 +135,17 @@ public class OrderDealService extends Service implements Handler.Callback{
132 135
                     int status = json.getInt("status");
133 136
                     if (status == 200) {
134 137
                         JSONObject data = json.getJSONObject("data");
135
-                        //TODO
138
+                        JSONObject file = data.getJSONObject("origin");
139
+                        PhotoBean bean = new PhotoBean();
140
+                        bean.photoName = file.getString("name");
141
+                        bean.photoId = file.getLong("id");
142
+                        bean.photoPath = file.getString("path");
143
+                        bean.captureTime = bean.photoId;
144
+                        bean.isRawPhoto = false;
145
+                        bean.uploadStatus =  PhotoBean.UploadStatus.STATUS_NO_BEGIN;
146
+                        bean.sessionId = orderBean.sessionId;
147
+                        bean.lensmanId = Preferences.getInstance().getLensManId();
148
+                        orderBean.photoBean = bean;
136 149
                     }
137 150
                     return true;
138 151
                 } catch (Exception e) {
@@ -144,14 +157,14 @@ public class OrderDealService extends Service implements Handler.Callback{
144 157
             @Override
145 158
             protected void onPostFail() {
146 159
                 super.onPostFail();
147
-                orderList.remove(bean);
160
+                orderList.remove(orderBean);
148 161
                 dealOrder();
149 162
             }
150 163
 
151 164
             @Override
152 165
             protected void onPostSuccess() {
153 166
                 super.onPostSuccess();
154
-                new SavePhotoTask(bean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), bean);
167
+                new SavePhotoTask(orderBean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), orderBean);
155 168
             }
156 169
         }.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.FETCH_ORIGIN_URL);
157 170
 
@@ -259,7 +272,7 @@ public class OrderDealService extends Service implements Handler.Callback{
259 272
         protected Boolean doInBackground(Void... params) {
260 273
             for (int k = 0; k < 5; k++) {
261 274
                 try {
262
-                    String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + bean.photoBean.sessionId
275
+                    String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + bean.sessionId
263 276
                             + File.separator + Constants.ORIGIN_DIR_NAME;
264 277
                     File dir = new File(dirPath);
265 278
                     dir.mkdirs();

:art: ThermometerMeasureInfo · e384a988d6 - Gogs: Go Git Service

:art: ThermometerMeasureInfo

huangqimin001 4 years ago
parent
commit
e384a988d6
1 changed files with 9 additions and 3 deletions
  1. 9 3
      api/eqpt_views.py

+ 9 - 3
api/eqpt_views.py

@@ -192,9 +192,12 @@ def upload_temperature(request):
192 192
     ThermometerMeasureLogInfo.objects.create(point_id=eqpt.point_id, macid=macid, name=name, sex=sex, birth_stamp=birth_stamp, phone=phone, start_stamp=start_stamp, end_stamp=end_stamp, temperature=temperature, upload_temperature_info=request.POST)
193 193
 
194 194
     if point_measure_window:
195
-        ThermometerMeasureInfo.objects.update_or_create(point_id=eqpt.point_id, point_measure_ymd=point_measure_ymd, point_measure_window=point_measure_window, macid=macid, defaults={
195
+        measure_info = ThermometerMeasureInfo.objects.get_or_create(point_id=eqpt.point_id, point_measure_ymd=point_measure_ymd, point_measure_window=point_measure_window, macid=macid, defaults={
196 196
             'temperature': temperature,
197 197
         })
198
+        if temperature > measure_info.temperature:
199
+            measure_info.temperature = temperature
200
+            measure_info.save()
198 201
 
199 202
     return response()
200 203
 
@@ -248,14 +251,17 @@ def mqtt_upload_temperature(payload):
248 251
         return
249 252
 
250 253
     point_measure_ymd = tc.local_string(format='%Y-%m-%d')
251
-    point_measure_window = point.current_measure_window
252 254
 
255
+    point_measure_window = point.current_measure_window
253 256
     eqpt.last_submit_at = tc.utc_datetime()
254 257
     eqpt.save()
255 258
 
256 259
     ThermometerMeasureLogInfo.objects.create(point_id=eqpt.point_id, macid=macid, start_stamp=start_stamp, end_stamp=end_stamp, temperature=temperature, temperature_src=ThermometerMeasureLogInfo.MQTT, upload_temperature_info=payload)
257 260
 
258 261
     if point_measure_window:
259
-        ThermometerMeasureInfo.objects.update_or_create(point_id=eqpt.point_id, point_measure_ymd=point_measure_ymd, point_measure_window=point_measure_window, macid=macid, defaults={
262
+        measure_info = ThermometerMeasureInfo.objects.get_or_create(point_id=eqpt.point_id, point_measure_ymd=point_measure_ymd, point_measure_window=point_measure_window, macid=macid, defaults={
260 263
             'temperature': temperature,
261 264
         })
265
+        if temperature > measure_info.temperature:
266
+            measure_info.temperature = temperature
267
+            measure_info.save()